class BinarySearch {

    /*
    二分查找的标准实现,要求输入一个带查找值以及一个升序的整数数组，返回待查找key的序号，找不到则返回-1
    */
    common() {
        if (arguments.length != 2) {
            throw Error('Arguments count error');
        }
        let key = parseInt(arguments[0], 10);
        let arr = arguments[1];
        if (isNaN(key) || !(arr instanceof Array)) {
            throw Error('Illegal arguments');
        }
        arr = arr.filter(arg => {
            return !isNaN(parseInt(arg, 10))
        }).map(arg => {
            return parseInt(arg, 10)
        });
        if (!arr.length) {
            throw Error('Illegal list');
        }

        //make sure array is ordered
        arr = arr.sort((a, b) => {
            return a - b
        });

        let low = 0,
            high = arr.length - 1;
        while (low <= high) {
            let middle = low + (high - low) / 2;
            if(key > arr[middle]) {
                low = middle + 1;
            }else  if(key < arr[middle]) {
                high = middle - 1;
            }else {
                return middle;
            }
        }
        return -1;
    }
}

module.exports = new BinarySearch();